<template>
  <div class="mp-home">
    <div class="guide">
      <div class="guide-title flex-box">
        <h3>使用指南</h3>
        <a href class="none close-guide">关闭指南</a>
      </div>
      <p class="guide-item">
        1、在【考勤设置】中使用方式二，即可设置打卡地点和Wifi。如何使用考勤打卡？
        <a href>查看帮助</a>
      </p>
      <p class="guide-item">
        2、设置打卡地址后，可在【排班管理】
        <a href="/attendance/work/schedule/group/list">“考勤组管理”</a>中关联员工及其适用的打卡地址
      </p>
    </div>

    <div class="mode-tab mt32">
      <div class="mode-tab-nav flex-box">
        <div class="t-n-item" :class="{active: tabActive === 0}" @click="tabChange(0)">打卡地址</div>
        <div class="t-n-item" :class="{active: tabActive === 1}" @click="tabChange(1)">打卡WiFi</div>
      </div>
      <div class="mode-tab-content mt32">
        <div class="m-t-c-item" v-if="tabActive === 0">
          <div class="m-i-header mb32 flex">
            <div class="left">
              <!-- <Input search enter-button placeholder="请输入打卡地址名称." class="form-input" /> -->
            </div>
            <div class="right">
              <Button class="save-btn-green" @click="openAddressModal">新增打卡地址</Button>
            </div>
          </div>
          <Table width="100%" :columns="columns" :data="addressList" class="table4" :loading="tableLoading"></Table>
        </div>
        <div class="m-t-c-item" v-if="tabActive === 1">
          <div class="m-i-header mb32 flex">
            <div class="left">
              <!-- <Input search enter-button placeholder="请输入打卡WiFi名称." class="form-input" /> -->
            </div>
            <div class="right">
              <Button class="save-btn-green" @click="openWifiModal">新增打卡WiFi</Button>
            </div>
          </div>
          <Table width="100%" :columns="wifi_columns" :data="wifiList" class="table4" :loading="tableLoading"></Table>
        </div>
      </div>

      
    </div>
    <!-- modal  -->
      <Modal v-model="modal2" width="720">
        <p slot="header" style="font-weight:bold;">新增打卡WiFi</p>
        <div class="m-c-content">
          <Form :model="formItem" :label-width="110" ref="formValidate" :rules="formValidate">
            <div class="form-item-row none">
              <FormItem label="ci_id" prop="wifi_name" style="display:none;">
                <Input v-model="formItem.ci_id" placeholder="请输入..." class="form-input"></Input>
              </FormItem>
            </div>
            <div class="form-item-row">
              <FormItem label="WiFi名称" prop="wifi_name">
                <Input v-model="formItem.wifi_name" placeholder="请输入..." class="form-input"></Input>
              </FormItem>
            </div>
            <div class="form-item-row2">
              <FormItem label="BBSID" class="form-item" required>
                <Input v-model="formItem.id1" placeholder maxlength="2" class="form-input-60"></Input>
                <span class="semicolon">:</span>
                <Input v-model="formItem.id2" placeholder maxlength="2" class="form-input-60"></Input>
                <span class="semicolon">:</span>
                <Input v-model="formItem.id3" placeholder maxlength="2" class="form-input-60"></Input>
                <span class="semicolon">:</span>
                <Input v-model="formItem.id4" placeholder maxlength="2" class="form-input-60"></Input>
                <span class="semicolon">:</span>
                <Input v-model="formItem.id5" placeholder maxlength="2" class="form-input-60"></Input>
                <span class="semicolon">:</span>
                <Input v-model="formItem.id6" placeholder maxlength="2" class="form-input-60"></Input>
              </FormItem>
              <div class="error" v-if="wifi_error">请填写正确的 wifi 地址</div>
            </div>
          </Form>

          <div class="getway" v-if="showWifiTip">
            <div class="left">
              <div class="title">获取方式：</div>
              <div class="content-wrap">
                <p>1.可以向公司IT部门询问公司WiFi的BSSID</p>
                <p>2.也可以使用微信扫描右侧二维码获取</p>
                <p>3.扫码前，请确认您是该企业的员工</p>
                <p>4.若企业的WiFi有多个，或有WiFi同名，为了保证打卡，请添加所有WiFi</p>
              </div>
            </div>
            <div class="right">
              <img src="@/assets/images/mp-qrcode.png" alt />
            </div>
          </div>
        </div>
        <div slot="footer">
          <div class="m-c-footer flex">
            <div class="m-c-left">
              <!-- <span>没有找到想要的项目？ </span>
              <span class="ml12"><a href="">去添加项目</a></span>-->
            </div>
            <div class="m-c-right">
              <Button @click="cancel" class="no-border-btn">取消</Button>
              <Button class="save-btn-green" @click="addWifiConfirm">确认</Button>
            </div>
          </div>
        </div>
      </Modal>

      <!--  -->
      <Modal v-model="modal3" width="720" class="selecte-modal">
        <p slot="header" style="font-weight:bold;">选择部门</p>
        <div class="m-c-content flex-box">
          <div class="selecte-modal-left">
            <Tabs value="name2" name="tab2">
              <TabPane label="选择部门" tab="tab2" name="name1">
                <div class="tab-content">
                  <Input search placeholder="请输入关键字" />
                  <div class="s-tree">
                    <!-- <Tree :data="data2" show-checkbox></Tree> -->
                  </div>
                </div>
              </TabPane>
              <TabPane label="最近选择" tab="tab2" name="name2">
                <div class="tab-content-2">
                  <ul class="lately-group">
                    <div class="mark-bar"></div>
                    <li class="lately-item flex-box">
                      <label for>
                        <Checkbox></Checkbox>
                      </label>
                      <div class="right-info flex-box">
                        <Icon type="md-folder" size="30" color="#c0dffe" class="mr12" />行政部（2人）
                      </div>
                    </li>
                  </ul>
                </div>
              </TabPane>
            </Tabs>
          </div>
          <div class="selecte-modal-right">
            <div class="s-r-header flex-box">
              <div class="s-r-header-left flex-box">
                <div class="s-r-h-title mr12">已选：</div>
                <div class="s-r-h-detail">
                  部门1个
                  <Icon type="md-close-circle" size="14" />
                </div>
              </div>
            </div>
            <div class="s-r-list">
              <div class="s-r-l-item">
                <Icon type="md-folder" size="30" color="#c0dffe" class="mr12" />
                <div class="s-r-l-item-name">
                  <span class="ellipse">行政部</span>
                </div>
                <div class="close-right-icon">
                  <Icon type="md-close" />
                </div>
              </div>
              <div class="s-r-l-item">
                <Icon type="md-folder" size="30" color="#c0dffe" class="mr12" />
                <div class="s-r-l-item-name">
                  <span class="ellipse">行政部</span>
                </div>
                <div class="close-right-icon">
                  <Icon type="md-close" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer">
          <div class="m-c-footer flex">
            <div class="m-c-left">
              <!-- <span>没有找到想要的项目？ </span>
              <span class="ml12"><a href="">去添加项目</a></span>-->
            </div>
            <div class="m-c-right">
              <Button @click="cancel" class="no-border-btn">取消</Button>
              <Button class="save-btn-green" @click="confirm">确认</Button>
            </div>
          </div>
        </div>
      </Modal>
      <!--  -->

      
      <Modal v-model="addressModal" width="720" class="selecte-modal">
        <p slot="header" style="font-weight:bold;">新增打卡地址</p>
        <div class="m-c-content">
            <input type="text" id="tipinput" class="map-search ivu-input" placeholder="请输入打卡地点" ref="inp"/> 
          <div class="map-wrap">
            <div id="map" ref="map"></div>
          </div>
          <div class="address-form">
            <Form class="address-form" :model="addressForm" :label-width="120" ref="addressForm" :rules='addressRule'> 
               <FormItem label="打卡地点名称" class="form-item form-item2" prop="ci_place">
                  <Input v-model="addressForm.ci_place" placeholder="请输入" maxlength="20" class="form-input"></Input>
                  <div class="address-tip">
                    打卡地址名称默认是您搜索的地点名称，您可以修改
                  </div>
                </FormItem>
                <FormItem label="实际打卡地址" class="form-item" prop="ci_address">
                 {{addressForm.ci_address}}
                </FormItem>
                 <FormItem label="打卡范围" class="form-item" prop="ci_scope">
                   <Select v-model="addressForm.ci_scope" class="form-input">
                      <Option value="100米">100米</Option>
                      <Option value="150米">150米</Option>
                      <Option value="200米">200米</Option>
                      <Option value="250米">250米</Option>
                      <Option value="300米">300米</Option>
                    </Select>
                </FormItem>
            </Form>
          </div>
        </div>
        <div slot="footer">
          <div class="m-c-footer flex">
            <div class="m-c-left">
              <!-- <span>没有找到想要的项目？ </span>
              <span class="ml12"><a href="">去添加项目</a></span>-->
            </div>
            <div class="m-c-right">
              <Button @click="cancel" class="no-border-btn">取消</Button>
              <Button class="save-btn-green" @click="savaAddress">确认</Button>
            </div>
          </div>
        </div>
      </Modal>
  </div>
</template>
<script>
import { attendance } from "@/apis";
import http from "@/utils/http";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      tabActive: 0,
      modal3: false,
      modal2: false,
      wifi_error: false,
      showWifiTip: false,
      addressModal: false,
      columns: [
        // {
        //   type: "selection",
        //   width: 60,
        //   align: "center"
        // },
        {
          title: "打卡地址",
          key: "ci_place"
        },
        {
          title: "具体地址",
          key: "ci_address"
        },
        {
          title: "可打卡范围",
          key: "ci_scope"
        },

        {
          title: "操作",
          key: "action",
          width: "120",
          render: (h, params) => {
            return h("div", [
              h(
                "a",
                {
                  props: {
                    type: "text",

                    className: "table-action-btn"
                  },
                  class: "table-action-btn",
                  on: {
                    click: () => {
                      this.editAddress(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "a",
                {
                  props: {
                    type: "text",

                    className: "table-action-btn"
                  },
                  class: "table-action-btn",
                  on: {
                    click: () => {
                      this.delete(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data4: [
        {
          name: "深圳市南山区人民政府",
          age: "桃园路2号",
          province: "300"
        }
      ],
      wifi_columns: [
        // {
        //   type: "selection",
        //   width: 60,
        //   align: "center"
        // },
        {
          title: "WiFi名称",
          key: "wifi_name"
        },
        {
          title: "Mac地址",
          key: "wifi_mac"
        },
        {
          title: "操作",
          key: "action",
          width: "120",
          render: (h, params) => {
            return h("div", [
              h(
                "a",
                {
                  props: {
                    type: "text",

                    className: "table-action-btn"
                  },
                  class: "table-action-btn",
                  on: {
                    click: () => {
                      this.editWifi(params.row,0);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "a",
                {
                  props: {
                    type: "text",

                    className: "table-action-btn"
                  },
                  class: "table-action-btn",
                  on: {
                    click: () => {
                      this.delete(params.row,1);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      Map: null,
      addressForm: {
       ci_type:"打卡地址",
       ci_place:"",
       ci_address:"",
       ci_scope:"300米",
      },
      formItem: {
       ci_type:"打卡WiFi",
       ci_id:"",
       wifi_name:"",
      },
      formValidate: {
        wifi_name: [
          { required: true, message: "请填写wifi名称", trigger: "blur" }
        ]
      },
      addressRule:{
        ci_place: [
          { required: true, message: "请在地图中输入企业地点，以便获取地址信息", trigger: "blur" }
        ],
        ci_address: [
          { required: true, message: "打卡地点名称不能为空", trigger: "blur" }
        ],
        ci_scope: [
          { required: true, message: "请选择打卡范围", trigger: "blur" }
        ]
      },
      wifiList: [],
      addressList: [],
      marker:"",
      circle:"",
      tableLoading: false
    };
  },
  methods: {
    openRightCard() {},
    cancel() {
      this.modal2 = false;
      this.addressModal = false;
    },
    detail() {
      this.modal2 = false;
      this.$router.push("/socialsecurity/insurance/monthly");
    },
    add() {
      this.modal2 = true;
    },
    confirm() {},
    openWifiModal() {
      this.modal2 = true;
      this.showWifiTip = true;
    },
    tabChange(e) {
      this.tabActive = e;
    },
    openAddressModal() {
      this.addressModal = true;
     
    },


    // 添加wifi 保存
    addWifiConfirm() {
      this.$refs["formValidate"].validate(valid => {
        if (valid) {
          let form = this.formItem;
          if (
            !form.id1 ||
            !form.id2 ||
            !form.id3 ||
            !form.id4 ||
            !form.id5 ||
            !form.id6
          ) {
            this.wifi_error = true;
          } else {
            this.wifi_error = false;
            let bbsid =
              form.id1 +
              ":" +
              form.id2 +
              ":" +
              form.id3 +
              ":" +
              form.id4 +
              ":" +
              form.id5 +
              ":" +
              form.id6;
            let postform = {
              ci_type: "wifi打卡",
              wifi_name: form.wifi_name,
              wifi_mac: bbsid,
              ci_id: form.ci_id
            };
            http
              .post(attendance.clockincreate, { data: postform })
              .then(res => {
                if (res.e == "9999") {
                  this.$Message.success("添加成功!");
                  this.modal2 = false;
                  this.getList(); //更新数据
                  this.formItem.ci_id ="";//清空打卡id，防止编辑和新增混乱
                } else {
                  this.$Message.error(res.m);
                }
              });
          }
        } else {
          this.$Message.error("Fail!");
        }
      });
    },

    // 获取打卡方式列表
    getList() {
      this.tableLoading = true;
      http.get(attendance.clockinlist, {}).then(res => {
        let d = res.data.list.data;
        if (d.length) {
          let wifiList = [];
          let addressList = [];
          d.forEach(e => {
            if (e.wifi_name) {
              wifiList.push(e);
            } else {
              addressList.push(e);
            }
          });
          this.wifiList = wifiList;
          this.addressList = addressList;
          this.tableLoading = false;
        }
      });
    },

    // wifi 编辑
    editWifi(e) {
      let bbsid = e.wifi_mac.split(":");
      if (bbsid.length == 6) {
        e.id1 = bbsid[0];
        e.id2 = bbsid[1];
        e.id3 = bbsid[2];
        e.id4 = bbsid[3];
        e.id5 = bbsid[4];
        e.id6 = bbsid[5];
      }
      this.formItem = e;
      this.modal2 = true;
      this.showWifiTip = false;
    },

    // 地图初始化 
    initMap() {
      let _this = this;
      AMapLoader.load({
        key: "a86c88b709920f366ef6de0503218db2",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.MouseTool",
          "AMap.PolyEditor",
          "AMap.RectangleEditor",
          "AMap.DistrictLayer",
          "AMap.CustomLayer",
          "AMap.Autocomplete",
          "AMap.PlaceSearch",
          "AMap.Geocoder",
          "AMap.OverView",
          "AMap.Scale"
        ] //插件列表
      })
        .then(AMap => {
         let map = new AMap.Map(this.$refs.map,{
            center: [116.397428, 39.90923], // [纬度，经度]
            resizeEnable: true,
            zoom: 12
         });
         this.Map = map;
         AMap.plugin(['AMap.AutoComplete','AMap.PlaceSearch'], function(){
            var autoOptions = {
              input: _this.$refs.inp
            };
            var autocomplete= new AMap.AutoComplete(autoOptions)

            var placeSearch = new AMap.PlaceSearch({
              map:map,
              marker:false,
            })
            autocomplete.on('select', function(e){
              //TODO 针对选中的poi实现自己的功能
              console.log(e.poi);
              let lng = e.poi.location.lng;
              let lat = e.poi.location.lat;
              _this.addressForm.ci_place = e.poi.name;
              _this.addressForm.longitude = lng;
              _this.addressForm.latitude = lat;
              _this.addressForm.ci_address =e.poi.district + e.poi.address;
              placeSearch.search(e.poi.name,function(e){
                placeSearch.clear();
              });
              _this.location(lng, lat)
            })
          })
        })
        .catch(e => {
          console.log(e);
        });
     
    },

    // 更新地图
    updateMap(lng,lat){
      this.location(lng,lat);
    },

    // 地址设置和获取
    location(lng, lat) {
      let map = this.Map;
      map.setZoomAndCenter(15, [lng, lat]);
      if(this.marker){
        map.remove(this.marker)
      }
      if(this.circle){
        map.remove(this.circle)
      }
      this.marker  = new AMap.Marker({
        map: map,
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
        position: [lng, lat],
      });
      this.circle  = new AMap.Circle({
        map: map,
        center: new AMap.LngLat(lng, lat), // 圆心位置
        radius: 1000, //半径
        strokeColor: "#F33", //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: "#ee2200", //填充颜色
        fillOpacity: 0.35 //填充透明度
      });

     
    },

    // 选择地址保存
    savaAddress(){
      this.$refs["addressForm"].validate(valid => {
        if (valid) {
          let form = this.addressForm;
          console.log(form);
           http
              .post(attendance.clockincreate, { data: form })
              .then(res => {
                if (res.e == "9999") {
                  this.$Message.success("添加成功!");
                  this.addressModal = false;
                  this.getList(); //更新数据
                  this.addressForm.ci_id ="";//清空打卡id，防止编辑和新增混乱
                } else {
                  this.$Message.error(res.m);
                }
              });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },

    // 地址编辑
    editAddress(e){
      let form = {};
      form.ci_id = e.ci_id;
      form.ci_type = e.ci_type;
      form.ci_place = e.ci_place;
      form.ci_address = e.ci_address;
      form.ci_scope = e.ci_scope;
      form.lng = e.lng;
      form.lat = e.lat;
      this.addressForm = form;
      this.updateMap(e.longitude,e.latitude)
      this.addressModal = true;
    
      // this.showWifiTip = false;
    },

    // 删除打卡方式
    delete(e,type){
      let title = "删除打卡地址";
      let content = "你确定要删除此打卡地址吗？"
      let _this = this;
      if(type){//0是地址，1是wifi
        title = "删除打卡WiFI";
        content ="你确定要删除此打卡WiFI吗？"
      }
      this.$Modal.confirm({
          title: title,
          content: content,
          onOk: () => {
            http
              .get(attendance.clockindelete, { params: {ci_id:e.ci_id} })
              .then(res => {
                if (res.e == "9999") {
                  _this.$Message.success("删除成功！");
                  _this.getList(); //更新数据
                } else {
                  _this.$Message.error(res.m);
                }
              });
          },
          onCancel: () => {
               
          }
      });
    }
  },
  mounted() {
    this.getList();
    this.initMap();
  }
};
</script>
<style lang="scss" scoped src="../index.scss">
</style>